package com.tanhua.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.constant.CacheKey;
import com.tanhua.domain.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头Authorization
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            response.setStatus(401);
            return false;
        }
        //从中得到token
        String token = authorization.replace("Bearer ", "");
        //从redis中获取当前用户
        String adminJson = redisTemplate.opsForValue().get(CacheKey.TOKEN_PREFIX + token);
        if (adminJson == null) {
            response.setStatus(401);
            return false;
        }
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX+token,adminJson, Duration.ofHours(1));
        //把当前用户和token绑定到当前线程
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeAdmin();
        AdminHolder.remoceToken();
    }
}
